/**
 * Created by liupan on 2017-3-8.
 * 模板配置界面js
 * 对应JSP为template.jsp
 */
define(["require", "jquery", "public/app"], function (require, $, app) {

    function Template($container) {
        this._$container = $container;
        this._init();
    }

    Template.prototype._initUrlPath = function () {
        this.urlPaths = {
            TemplateData: app.urlBuild("/dirms/monitor/template/all"),
            IconsData: app.urlBuild("/dirms/monitor/icons/all"),
            IconsTemplateData: app.urlBuild("/dirms/monitor/icons/getTemplateIcons"),
            TemplateEdit: app.urlBuild("/pages/app/config/templateEdit.jsp"),
            UpdateTemplateData: app.urlBuild("/dirms/monitor/template/update"),
            HostGroupData: app.urlBuild("/dirms/monitor/group/list"),
            TemplateHostGroupData: app.urlBuild("/dirms/monitor/group/templatelist"),
            QueryTemplateByGroupId: app.urlBuild("/dirms/monitor/template/queryByGroupId/"),
            QueryTemplateByName: app.urlBuild("/dirms/monitor/template/queryByName/"),
            SaveTemplateIcons: app.urlBuild("/dirms/monitor/templateAndIcons/saveList")
        }
    };

    Template.prototype._init = function () {
        this._initUrlPath();
        // this._initComponents();
        var self = this;
        var dataReady = app.getDataReady();

        dataReady.pushDataSource({//逐个放入所有数据源
            url: this.urlPaths.TemplateData,
            key: 'TemplateData'
        });

        dataReady.pushDataSource({//逐个放入所有数据源
            url: this.urlPaths.IconsTemplateData,
            key: 'IconsTemplateData'
        });

        dataReady.once(function (readyData) {
            self._initComponents(readyData);
        });
    };

    Template.prototype._initComponents = function (readyData) {
        //初始化控件
        this._initTemplateGrid(readyData);//初始化用户表格
        this._initEventBinding(this);//初始化事件绑定
        this._initSearch();//初始化搜索
    };

    var TemplateGrid;
    Template.prototype._initSearch = function () {
        var self = this;
        //主表格搜索框
        $('#searchMenu').searchbox({
            //搜索功能未完成，应按照用户、角色、组织机构三类来进行搜索
            searcher: function (value, name) {
                if(name == 'name' && value != ""){
                    $.ajax({
                        type: "POST",
                        url: self.urlPaths.QueryTemplateByName + value,
                        success:function(data){
                            if(data == ""||data == null){alert(value+" 模板不存在");}
                            else{
                                $('#templateGrid').datagrid('loadData',data);
                                $('#searchMenu').searchbox('clear');
                            }
                        },
                        error:function(){alert("查询错误");}
                    });
                }
                // else{
                //     $('#_UserGrid').datagrid('reload');
                // }
            },
            menu: '#search',
            prompt: '请输入关键字'
        });
    };
    //初始化表格
    Template.prototype._initTemplateGrid = function (readyData) {
        var self = this;

        $("#hostgroups").combobox({
            url: self.urlPaths.TemplateHostGroupData,
            // data: [{"groupid":"-1","name":"所有",selected:true}],
            valueField: "groupid",
            textField: "name",
            method: 'get',
            editable: true,
            required: true,
            onSelect:function(record){
                var queryUrl = "";
                if (record.groupid == -99) {
                    queryUrl = self.urlPaths.TemplateData;
                } else {
                    queryUrl = self.urlPaths.QueryTemplateByGroupId + record.groupid;
                }

                $.ajax({
                    url: queryUrl,
                    type: "POST",
                    cache: false,
                    contentType: "application/json",
                    async : false,
                    beforeSend:function(XMLHttpRequest){
                        $.messager.progress({
                            title : '提示信息！',
                            text : '数据处理中，请稍后....'
                        });
                    },
                    success: function(data){
                        $.messager.progress('close');
                        if(typeof(data) != "undefined" && data != null && data != ''){
                            var tmpData = [];
                            $.each(data.result, function (index) {
                                var iconsTemplateData = readyData.IconsTemplateData.data;
                                var deviceImgName = "",deviceId = "";
                                if (iconsTemplateData.hasOwnProperty(this.templateid)) {
                                    deviceImgName = iconsTemplateData[this.templateid].name;
                                    deviceId = iconsTemplateData[this.templateid].id;
                                }
                                this.icon = deviceImgName;
                                this.iconname = deviceImgName;
                                this.iconid = deviceId;
                                tmpData.push(this);
                            });

                            $("#templateGrid").datagrid('loadData',tmpData);//重新加载列表数据
                        }
                    },
                    error: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
                        $.messager.progress('close');
                        $.messager.alert('提示','数据获取失败！','info')
                    }
                });
            }
        });
        var templateData = [];
        $.each(readyData.TemplateData.data.result, function (index) {
            var iconsTemplateData = readyData.IconsTemplateData.data;
            var deviceImgName = "",deviceId = "";
            if (iconsTemplateData.hasOwnProperty(this.templateid)) {
                deviceImgName = iconsTemplateData[this.templateid].name;
                deviceId = iconsTemplateData[this.templateid].id;
            }
            this.icon = deviceImgName;
            this.iconname = deviceImgName;
            this.iconid = deviceId;
            templateData.push(this);
        });

        self.editIndex = undefined;

        function onClickRow(index){
            if (self.editIndex != index){
                if (self._endEditTemplate()){
                    $('#templateGrid').datagrid('selectRow', index)
                        .datagrid('beginEdit', index);
                    self.editIndex = index;
                } else {
                    $('#templateGrid').datagrid('selectRow', self.editIndex);
                }
            }
        }

        //主页面用户信息表格
        TemplateGrid=$('#templateGrid').datagrid({
            rownumbers: true,
            pagination: true,
            singleSelect: true,
            // fitColumns: true,
            // url: this.urlPaths.TemplateData,
            data: templateData,
            method: 'get',
            title: '',
            width: 'auto',
            height: '100%',
            region: 'south',
            //对应model层字段
            columns: [[
                {field:'templateid',title:"模板编号",width: '100'},
                {field: 'name', title: '模板名称', width: '200'},
                {field: 'icon', title: '关联图标', width: '200', formatter: function (value, row, index) {
                    // return row.iconname;
                    return '<img src="'+app.getDeviceImgPath() + row.iconname + '" />';
                }, editor:{
                    type: 'combobox',
                    options: {
                        // data: [{"value":"icon1","text":"gf1"},{"value":"icon2","text":"gf2"},{"value":"icon3","text":"gf3"}],
                        valueField: "id",
                        textField: "name",
                        method: 'get',
                        url: self.urlPaths.IconsData,
                        editable: true,
                        required: true,
                        formatter: function(value, row, index){
                            // return value.name;
                            return '<img src="'+app.getDeviceImgPath() + value.name + '" />';
                        }
                    }
                }},
                // {field: 'icon', title: '关联图标', width: '100', editor:{
                //     type: 'combobox',
                //     options: {
                //         // data: [{"value":"icon1","text":"gf1"},{"value":"icon2","text":"gf2"},{"value":"icon3","text":"gf3"}],
                //         valueField: "value",
                //         textField: "name",
                //         method: 'get',
                //         url: self.urlPaths.IconsData,
                //         editable: true,
                //         required: true,
                //         formatter: function(value, row, index){
                //             // return value.name;
                //             return '<img src="'+app.getBasePath() + '/images/app/topo/host.png" />';
                //         }
                //     }
                // }},
            ]],
            toolbar: this._$container.find("#Toolbar"),
            onClickRow: onClickRow
        });
    };

    /**
     * 结束编辑模板
     */
    Template.prototype._endEditTemplate = function () {
        var self = this;
        if (self.editIndex == undefined){return true}
        if ($('#templateGrid').datagrid('validateRow', self.editIndex)){
            var ed = $('#templateGrid').datagrid('getEditor', {index:self.editIndex,field:'icon'});
            var name = $(ed.target).combobox('getText');
            var value = $(ed.target).combobox('getValue');
            $('#templateGrid').datagrid('getRows')[self.editIndex]['icon'] = name;
            $('#templateGrid').datagrid('getRows')[self.editIndex]['iconname'] = name;
            $('#templateGrid').datagrid('getRows')[self.editIndex]['iconid'] = value;
            $('#templateGrid').datagrid('endEdit', self.editIndex);
            self.editIndex = undefined;
            return true;
        } else {
            return false;
        }
    };


        /**
         * 事件绑定
         */
        Template.prototype._initEventBinding = function (self) {
            //【todo 在此编写绑定事件的方法。如按钮需要绑定的click事件。建议按如下格式绑定，并将this作为参数传入】
            //egg
            //用户管理首页五个按钮
            // this._$container.find('#adduser_btn').on('click', {self: this}, this._actions.adduserClick);
            this._$container.find('#edittemplate_btn').on('click', {self: this}, this._actions.editTemplateClick);
            // this._$container.find('#deleteuser_btn').on('click', {self: this}, this._actions.deleteuserClick);
            this._$container.find('#accepttemplate_btn').on('click', {self: this}, this._actions.acceptTemplateClick);
            this._$container.find('#rejecttemplate_btn').on('click', {self: this}, this._actions.rejectTemplateClick);
        };


        /**
         * 在此定义此js用到的事件处理方法。如处理按钮click事件的方法
         * @type {{btcClick: Function}}
         */
        Template.prototype._actions = {
            //模板编辑按钮事件
            editTemplateClick: function(evt){
                //获取这一行内容
                var row = $("#templateGrid").datagrid('getSelections');
                if (row == undefined||row.length==0 ) {
                    $.messager.alert('提示',"请选择编辑对象",'info');
                    return;
                }else if(row.length>1){
                    $.messager.alert('提示',"只能选择单条记录",'info');
                    return;
                }
                showTemplateDialog(evt,row);
            },
            acceptTemplateClick: function (evt) {
                if (evt.data.self._endEditTemplate()){
                    var changes = $('#templateGrid').datagrid('getChanges');
                    var dataJson = [];
                    $.each(changes, function (index) {
                        var dataMap = {};
                        dataMap.iconsId = this.iconid;
                        dataMap.templateId = this.templateid;
                        dataJson.push(dataMap);
                    });

                    $.ajax({
                        url: evt.data.self.urlPaths.SaveTemplateIcons,
                        type: "POST",
                        cache: false,
                        contentType: "application/json",
                        dataType: "json",
                        data : JSON.stringify(dataJson),
                        success: function(data){
                            $('#templateGrid').datagrid('acceptChanges');
                            $.messager.alert('提示：','修改成功');
                        },
                        error: function () {
                            $('#templateGrid').datagrid('rejectChanges');
                            evt.data.self.editIndex = undefined;
                            $.messager.alert('提示','修改失败！','info');
                        }
                    });
                }
            },
            rejectTemplateClick: function (evt) {
                $('#templateGrid').datagrid('rejectChanges');
                evt.data.self.editIndex = undefined;
            }
        };

        /**
         *
         * @param evt 点击时间
         * @param row  行记录数据
         */
        var showTemplateDialog = function(evt,row){
            var inputUrl = evt.data.self.urlPaths.TemplateEdit;
            var iconDataUrl = evt.data.self.urlPaths.IconsData;
            if (typeof(row) == 'undefined' || row.length != 1) {
                return;
            }
            var title="编辑模板";
            //对话框
            var templateEditdialog = $('<div id="template-edit"/>').dialog({
                title : title,
                top:100,
                width : 500,
                /*          height : 360,*/
                modal : true, //模式窗口：窗口背景不可操作
                resizable : false, //可拖动边框大小
                plain : true,
                href : inputUrl,
                buttons : [ {
                    text : '确定',
                    iconCls : 'icon-ok',
                    plain : true,
                    handler : function() {
                        var templateData = $("#templateEdit").serializeJsonStr();

                        var isValid = $('#templateEdit').form('validate');
                        if(!isValid){
                            return ;
                        }
                        $.ajax({
                            url:evt.data.self.urlPaths.UpdateTemplateData,
                            type:"POST",
                            cache:false,
                            contentType: "application/json",
                            async : false,
                            dataType: "json",
                            data : templateData,
                            beforeSend:function(XMLHttpRequest){
                                $.messager.progress({
                                    title : '提示信息！',
                                    text : '数据处理中，请稍后....'
                                });
                            },
                            success: function(data){
                                $.messager.progress('close');
                                if(typeof(data) != "undefined" && data !=null && data!=''){
                                    $.messager.alert('提示','保存成功！','info');
                                    $("#templateGrid").datagrid('reload');//重新加载列表数据
                                    $("#template-edit").dialog('destroy');//销毁对话框
                                }
                            },
                            error: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
                                $.messager.progress('close');
                                $.messager.alert('提示','数据保存失败！','info')
                            }
                        });
                    }
                }, {
                    text : '取消',
                    iconCls : 'icon-cancel',
                    plain : true,
                    handler : function() {
                        $("#template-edit").dialog('destroy');//销毁对话框
                    }
                } ],
                onClose : function() {
                    $(this).dialog('destroy');
                },
                onLoad : function() {
                    /*user_input_form_init(evt);*/
                    //编辑
                    if(row != undefined && row.length==1){
                        // var id=row[0].id;
                        $("#icon").combobox({
                            url: iconDataUrl,
                            valueField: "value",
                            textField: "name",
                            method: 'get',
                            editable: true,
                            required: true,
                        });
                        $("#templateEdit").form("load",row[0]);
                        // $('#id').val(id);
                    }
                }
            }).dialog('open');
        };

        return Template;
    });
